package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Brand;
import com.bwie.service.BrandService;
import com.bwie.mapper.BrandMapper;
import com.bwie.utils.R;
import com.bwie.vo.BrandVo;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
* @author 陶仕豪
* @description 针对表【tb_brand(品牌表)】的数据库操作Service实现
* @createDate 2025-07-19 09:43:21
*/
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand>
    implements BrandService{
    @Autowired
    BrandMapper brandMapper;

    @Autowired
    HttpServletRequest request;

    @Override
    public R getBrandList(BrandVo brandVo) {
        Page<Brand> brandPage = new Page<>(brandVo.getPageNum(), brandVo.getPageSize());
        QueryWrapper<Brand> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(Brand::getCreateTime);
        if(StringUtils.isNotEmpty(brandVo.getBrandName())){
            wrapper.lambda().like(Brand::getBrandName,brandVo.getBrandName());
        }

        Page<Brand> page = brandMapper.selectPage(brandPage,wrapper);
        return R.OK(page);
    }

    @Override
    public R updateBrandStatus(Brand tbBrand) {
        String token = request.getHeader("token");
        if(token==null){
            return R.ERROR(500,"请先登录");
        }
        Brand brand = brandMapper.selectById(tbBrand.getBrandId());
        if(brand==null){
            return R.ERROR(500,"品牌不存在");
        }
        String userName = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("userName", String.class);

        brand.setBrandStatus(tbBrand.getBrandStatus());
        brand.setUpdateBy(userName);
        brand.setUpdateTime(new Date());
        brandMapper.updateById(brand);
        return R.OK();
    }

    @Override
    public R addBrand(Brand brand) {
        String token = request.getHeader("token");
        if(token==null){
            return R.ERROR(500,"请先登录");
        }
        String userName = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("userName", String.class);
        brand.setCreateTime(new Date());
        brand.setCreateBy(userName);
        brandMapper.insert(brand);
        return R.OK(brand);
    }

    @Override
    public R getBrandAll() {
        List<Brand> brandList = brandMapper.selectList(null);
        return R.OK(brandList);
    }
}




